package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"strconv"
)

// 定义 handle 处理函数
func healthz(w http.ResponseWriter, req *http.Request) {
	//io.WriteString(w, "ok")
	fmt.Fprintf(w, "Hello,"+req.URL.Path[1:]+"\n") // 进入方法打印欢迎
	//fmt.Println("类型：%T", req.Header)
	//fmt.Println("in healthz")

	//将 request 中带的 header 写入 response header
	for k, v := range req.Header {
		//w.Header()[k] = v
		w.Header().Set(k, v[0])
	}

	//获取当前系统的环境变量中的 VERSION 配置，并写入 response header
	version, value := getLocalEnv()
	fmt.Println(version, value)
	w.Header().Add(version, value)

	// 输出response中的header内容
	fmt.Fprintln(w, "request 中带的 header 写入 response header:")
	for k, v := range w.Header() {
		fmt.Fprintln(w, k, v) // response header数据输出
	}
	retCode := http.StatusOK
	recordClientVisitLog(req, strconv.Itoa(retCode)) // server端打印日志
	fmt.Fprintln(w, "返回码：", retCode)                 // 打印返回码

}

func getLocalEnv() (string, string) {
	VERSION := os.Getenv("VERSION")
	//VERSION := os.Getenv("VSCODE_API_VERSION")

	if VERSION == "" {
		VERSION = "NO CONFIGED"
		// TODO
	}

	return "VERSION", VERSION
}

func recordClientVisitLog(req *http.Request, retCode string) {
	logInfo := map[string]string{
		"Host":       req.Host,
		"RemoteAddr": req.RemoteAddr,
	}
	//httpRetCode := http.StatusOK
	httpRetCode := retCode
	//logInfo["httpRetCode"] = strconv.Itoa(httpRetCode) // int -> string
	logInfo["httpRetCode"] = httpRetCode // int -> string
	result := logInfo["Host"] + "|" + logInfo["RemoteAddr"] + "|" + logInfo["httpRetCode"] + "\n"
	fmt.Println(result)

}
func main() {
	// 注册处理函数
	http.HandleFunc("/healthz", healthz)
	// 监听端口
	err := http.ListenAndServe("0.0.0.0:8080", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err.Error())
	}

}
